import { ref } from 'vue'
import { defineStore } from 'pinia'
import router from "@/router/index.js";
import {ElMessage} from "element-plus";

export const useNavStore = defineStore('nav', () => {
    // 存储导航列表
    const navList = ref([])

    // 添加导航
    const addNav = (nav) => {
        if (!nav) return ElMessage.error('添加导航错误')
        if (!nav.name || nav.name === '') return ElMessage.error('添加导航错误')
        if (!nav.path || nav.path === '') return ElMessage.error('添加导航错误')
        // 查看是否有重复的导航，有就不添加
        for (const navItem of navList.value) {
            if (navItem.name === nav.name) return
        }
        navList.value.push(nav)
    }

    // 删除导航
    const deleteNav = (index) => {
        if (index < 0 || index > navList.value.length) return
        navList.value.splice(index, 1)
        if (navList.value.length === 0) return router.push('/home')
        else router.push(navList.value[navList.value.length - 1].path)
    }

    // 清空导航数据
    const clearNav = () => {
        navList.value.splice(0)
    }

    return { navList, addNav, deleteNav, clearNav }
})
